<?php

use
    Phalcon\Mvc\Model\Behavior\SoftDelete;

class OaCustomers extends \Formax\Model
{

    const DELETED = 1;
    const NOT_DELETED = 0;

    const ASSIGNED = 1;
    const TO_BE_ASSIGNED = 2;
    const NO_FOLLOW_UP = 3;

    /**
     *
     * @var integer
     */
    public $customer_id;

    /**
     *
     * @var integer
     */
    public $type_id = 0;

    /**
     *
     * @var string
     */
    public $email = '';

    /**
     *
     * @var string
     */
    public $nickname = '';

    /**
     *
     * @var string
     */
    public $mobile = '';

    /**
     *
     * @var string
     */
    public $phone = '';

    /**
     *
     * @var integer
     */
    public $web_uid = 0;

    /**
     *
     * @var integer
     */
    public $reg_time = 0;

    /**
     *
     * @var integer
     */
    public $merchant_id = 0;

    /**
     *
     * @var integer
     */
    public $mt4_demo = 0;

    /**
     *
     * @var integer
     */
    public $mt4_live = 0;

    /**
     *
     * @var integer
     */
    public $country_id = 0;

    /**
     *
     * @var integer
     */
    public $last_deposited = 0;

    /**
     *
     * @var integer
     */
    public $creator = 0;

    /**
     *
     * @var integer
     */
    public $assign_id = 0;

    /**
     *
     * @var integer
     */
    public $assign_time = 0;

    /**
     *
     * @var integer
     */
    public $manager_user_id = 0;

    /**
     *
     * @var integer
     */
    public $sales_user_id = 0;

    /**
     *
     * @var integer
     */
    public $last_followed = 0;

    /**
     *
     * @var integer
     */
    public $deleted = 0;

    /**
     *
     * @var integer
     */
    public $ctime = 0;

    /**
     *
     * @var integer
     */
    public $mtime = 0;

    public function initialize()
    {
        $this->addBehavior(new SoftDelete(
            array(
                'field' => 'deleted',
                'value' => self::DELETED
            )
        ));
    }

    public function beforeCreate()
    {
        if (! $this->creator) {
            $this->creator = service('auth')->user_id;
        }

        parent::beforeCreate();
    }

    public function beforeValidation()
    {
        if (! trim($this->nickname)) {
            return $this->errorMessage('Nickname is required');
        }

        if ($find = self::findFirst("nickname='{$this->nickname}'")) {
            if ($find->customer_id != $this->customer_id) {
                return $this->errorMessage('Nickname already exists');
            }
        }

        if (! trim($this->email)) {
            return $this->errorMessage('Email is required');
        }

        if (! is_email($this->email)) {
            return $this->errorMessage('Invalid email address');
        }

        if ($find = self::findFirst("email='{$this->email}'")) {
            if ($find->customer_id != $this->customer_id) {
                return $this->errorMessage('Email already exists');
            }
        }

        parent::beforeValidation();
    }

    // 执行分配
    public function assignTo($assign_id, $manager_user_id, $sales_user_id = 0)
    {
        if ($this->customer_id && $assign_id && $manager_user_id) {
            $old_assign_id = $this->assign_id;

            $result = $this->save(array(
                'assign_id'       => $assign_id,
                'manager_user_id' => $manager_user_id,
                'sales_user_id'   => $sales_user_id,
                'assign_time'     => time(),
            ));

            OaCustomerAssigns::updateCustomerNums($assign_id);

            if ($old_assign_id) {
                OaCustomerAssigns::updateCustomerNums($old_assign_id);
            }

            return $result;
        }

        return false;
    }

    // 获取已使用的国家 id
    public static function getUsedCountries()
    {
        $result = self::find(array(
            'deleted = 0 and country_id > 0',
            'columns' => 'distinct country_id',
        ));

        return array_pick($result->toArray(), 'country_id');
    }

    // 获取统计数据(用于菜单侧栏)
    public static function getSideStatistics()
    {
        $statistics = array(
            'all'            => null,
            'assigned'       => self::ASSIGNED,
            'to-be-assigned' => self::TO_BE_ASSIGNED,
            'no-follow-up'   => self::NO_FOLLOW_UP,
        );

        foreach ($statistics as $key => $val) {
            $statistics[$key] = self::getFilterBuilder(array(
                    'assigned_to' => service('auth')->user_id,
                    'status' => $val
                ))
                ->getQuery()
                ->execute()
                ->count();
        }

        return $statistics;
    }

    public static function getFilterBuilder(array $filter = array())
    {
        $builder = self::getInstance()
            ->createBuilder()
            ->where('deleted = 0');

        if ($nickname = array_get($filter, 'nickname')) {
            $builder->andWhere("nickname like '%$nickname%'");
        }

        if ($type_id = array_get($filter, 'type_id')) {
            $builder->andWhere('type_id=' . $type_id);
        }

        if ($email = array_get($filter, 'email')) {
            $builder->andWhere("email like '%$email%'");
        }

        if ($mobile = array_get($filter, 'mobile')) {
            $builder->andWhere("mobile like '%$mobile%'");
        }

        if ($phone = array_get($filter, 'phone')) {
            $builder->andWhere("phone like '%$phone%'");
        }

        if ($country_id = array_get($filter, 'country_id')) {
            $builder->andWhere('country_id=' . $country_id);
        } else {
            $builder->inWhere('country_id', config('customer.allowCountries')->toArray());
        }

        if ($reg_time_from = array_get($filter, 'reg_time_from')) {
            if (is_date($reg_time_from)) {
                $reg_time_from .= ' 00:00:00';
                $builder->andWhere("reg_time >= " . strtotime($reg_time_from));
            }
        }

        if ($reg_time_to = array_get($filter, 'reg_time_to')) {
            if (is_date($reg_time_to)) {
                $reg_time_to .= ' 23:59:59';
                $builder->andWhere("reg_time <= " . strtotime($reg_time_to));
            }
        }

        if ($merchant_id = array_get($filter, 'merchant_id')) {
            $builder->andWhere('merchant_id=' . $merchant_id);
        } else {
            $builder->andWhere('merchant_id <> 17');
        }

        if ($web_uid = array_get($filter, 'web_uid')) {
            $builder->andWhere('web_uid=' . $web_uid);
        }

        if ($mt4_demo = array_get($filter, 'mt4_demo')) {
            $builder->andWhere('mt4_demo=' . $mt4_demo);
        }

        if ($mt4_live = array_get($filter, 'mt4_live')) {
            $builder->andWhere('mt4_live=' . $mt4_live);
        }

        if ($creator = array_get($filter, 'creator')) {
            $builder->andWhere('creator=' . $creator);
        }

        if ($manager = array_get($filter, 'manager_user_id')) {
            $builder->andWhere('manager_user_id=' . $manager);
        }

        if ($sales = array_get($filter, 'sales_user_id')) {
            $builder->andWhere('sales_user_id=' . $sales);
        }

        $user_id = array_get($filter, 'assigned_to');

        // 获取下属员工列表
        $sub_users = OaSales::getSubUsers($user_id);
        $sub_users_in = implode(',', $sub_users);
        $sub_managers = OaSales::getSubManagers($user_id);
        $sub_managers_in = implode(',', $sub_managers);

        if ($status = array_get($filter, 'status')) {
            // 已分配
            if ($status == self::ASSIGNED) {
                if (OaSales::isStaff($user_id)) {
                    $builder->andWhere("creator=$user_id or sales_user_id=$user_id");
                } elseif (OaSales::isManager($user_id)) {
                    $builder->andWhere("creator in ($sub_users_in) or manager_user_id in ($sub_managers_in) or sales_user_id in ($sub_users_in)");
                } else {
                    $builder->andWhere('creator>0 or sales_user_id>0');
                }
            }
            // 待分配
            elseif ($status == self::TO_BE_ASSIGNED) {
                if (OaSales::isManager($user_id)) {
                    $builder->andWhere("creator=0 and manager_user_id=$user_id and sales_user_id=0");
                } elseif (OaSales::isStaff($user_id)) {
                    $builder->andWhere("creator=0 and 0"); // 销售人员，无结果
                } else {
                    $builder->andWhere('creator=0 and sales_user_id=0');
                }
            }
            // 未跟进
            elseif ($status == self::NO_FOLLOW_UP) {
                $builder->andWhere('last_followed=0');
                if (OaSales::isStaff($user_id)) {
                    $builder->andWhere("creator=$user_id or sales_user_id=$user_id");
                } elseif (OaSales::isManager($user_id)) {
                    $builder->andWhere("creator in ($sub_users_in) or manager_user_id in ($sub_managers_in) or sales_user_id in ($sub_users_in)");
                } else {
                    $builder->andWhere('creator>0 or sales_user_id>0');
                }
            }
        }

        // 销售经理
        elseif (OaSales::isManager($user_id)) {
            $builder->andWhere("creator in ($sub_users_in) or manager_user_id in ($sub_managers_in) or sales_user_id in ($sub_users_in)");
        }

        // 销售人员
        elseif (OaSales::isStaff($user_id)) {
            $builder->andWhere("creator=$user_id or manager_user_id=$user_id or sales_user_id=$user_id");
        }

        return $builder;
    }

}
